package com.quanquan.store.service;


import DTO.PageDTO;
import DTO.image.Image;
import DTO.image.ImageDTO;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.quanquan.store.configBean.RabbitSender;
import com.quanquan.store.dto.IdDTO;
import com.quanquan.store.dto.StoreDTO;
import com.quanquan.store.dto.StoreInfoDTO;
import com.quanquan.store.entity.*;
import com.quanquan.store.exception.StoreException;
import com.quanquan.store.repository.*;
import com.quanquan.store.request.StoreRequest;
import commond.ImageOutPut;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import utils.DateUtils;
import utils.StringUtil;
import utils.StringUtils;
import utils.UUIDGenerator;

import javax.persistence.criteria.Predicate;
import java.util.*;


/**
 * 功能描述:
 *
 * @ClassName: Store
 * @Author: xiongjunbao
 * @Date: 2019-03-11 10:29
 * @Version: V1.0
 */
@Service
public class StoreService {

    private final StoreRepository storeRepository;
    private final CouponService couponService;
    private final HistoryService historyService;
    private final ConcernService concernService;
    private final AmqpTemplate amqpTemplate;
    private final RestTemplate restTemplate;
    private final CommercialRepository commercialRepository;
    private final FloorRepository floorRepository;
    private final ConcernRepository concernRepository;
    private final HistoryReposity historyReposity;
    private final RabbitSender rabbitSender;
    private final StoreLabelRepository storeLabelRepository;
    private final LabelRepository labelRepository;

    @Autowired
    public StoreService(StoreRepository storeRepository, AmqpTemplate amqpTemplate, FloorRepository floorRepository, ConcernRepository concernRepository, RestTemplate restTemplate, CouponService couponService, CommercialRepository commercialRepository, HistoryService historyService, ConcernService concernService, HistoryReposity historyReposity, RabbitSender rabbitSender, StoreLabelRepository storeLabelRepository, LabelRepository labelRepository) {
        this.storeRepository = storeRepository;
        this.amqpTemplate = amqpTemplate;
        this.floorRepository = floorRepository;
        this.concernRepository = concernRepository;
        this.restTemplate = restTemplate;
        this.couponService = couponService;
        this.commercialRepository = commercialRepository;
        this.historyService = historyService;
        this.concernService = concernService;
        this.historyReposity = historyReposity;
        this.rabbitSender = rabbitSender;
        this.storeLabelRepository = storeLabelRepository;
        this.labelRepository = labelRepository;
    }

    /**
     * 添加商户
     *
     * @param request
     * @return
     */
    public StoreDTO saveStore(StoreRequest request) {
        StoreDTO storeDTO = new StoreDTO();
        Store store = new Store();
        Date date = new Date();
        BeanUtil.copyProperties(request, storeDTO, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        store.setId(UUIDGenerator.getUUID());
        store.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        store.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        store.setStatusRemove(0);
//        store.setStatusShow(0);
        //绑定商户业态关系
        if (request.getCommercialId() != null) {
            Commercial commercial = commercialRepository.findByCommercialId(request.getCommercialId());
            store.setCommercialId(request.getCommercialId());
            store.setStoreCommercial(commercial.getName());
        }
        //绑定商户楼层关系
        if (request.getFloorId() != null) {
            store.setFloorId(request.getFloorId());
            Floor floor = floorRepository.findByIdAndStatusShow(request.getFloorId());
            store.setStoreFloor(floor.getFloorName());
        }
        //绑定商户标签关系
        if (request.getLabelIdList() != null && request.getLabelIdList().size() > 0) {
            StoreLabel storeLabel = new StoreLabel();
            for (String labelId : request.getLabelIdList()) {
                storeLabel.setId(UUIDGenerator.getUUID());
                storeLabel.setLabelId(labelId);
                storeLabel.setStoreId(store.getId());
                storeLabel.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                storeLabel.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                storeLabel.setStatusShow(0);
                storeLabel.setStatusRemove(0);
                storeLabelRepository.saveAndFlush(storeLabel);
            }
        }
        bandingImageShip(store.getId(), request.getImageIds());
        storeRepository.saveAndFlush(store);
        BeanUtils.copyProperties(store, storeDTO);
        return storeDTO;
    }


    /**
     * 新添加商户(xiaoqianh)
     *
     * @param request
     * @return
     */
    public StoreDTO createStore(StoreRequest request) {
        StoreDTO storeDTO = new StoreDTO();
        Store store = new Store();
        //通过映射关系来赋值 //TODO 断点看一下
        BeanUtils.copyProperties(request, store);
        store.setId(UUIDGenerator.getUUID());
        store.setCreateTime(DateUtils.currentDate());
        store.setUpdateTime(DateUtils.currentDate());
        store.setStatusRemove(0);
        store.setStatusShow(0);
        store.setStoreStatus(1);
        if (request.getCommercialId() != null) {
            Commercial commercial = commercialRepository.findByCommercialId(request.getCommercialId());
            store.setCommercialId(request.getCommercialId());
            store.setStoreCommercial(commercial.getName());
        }
        if (request.getFloorId() != null) {
            store.setFloorId(request.getFloorId());
            Floor floor = floorRepository.findByIdAndStatusShow(request.getFloorId());
            store.setStoreFloor(floor.getFloorName());
        }
        //绑定商户标签关系
        if (request.getLabelIdList() != null && request.getLabelIdList().size() > 0) {
            StoreLabel storeLabel = new StoreLabel();
            for (String labelId : request.getLabelIdList()) {
                storeLabel.setId(UUIDGenerator.getUUID());
                storeLabel.setLabelId(labelId);
                storeLabel.setStoreId(store.getId());
                storeLabel.setCreateTime(DateUtils.currentDate());
                storeLabel.setUpdateTime(DateUtils.currentDate());
                storeLabel.setStatusShow(0);
                storeLabel.setStatusRemove(0);
                storeLabelRepository.saveAndFlush(storeLabel);
            }
        }
        bandingImageShip(store.getId(), request.getImageIds());
        storeRepository.saveAndFlush(store);
        BeanUtils.copyProperties(store, storeDTO);
        return storeDTO;
    }

    /**
     * 绑定商户图片
     *
     * @param stroreId
     * @param imageIdlist
     */
    private void bandingImageShip(String stroreId, List<String> imageIdlist) {
        ImageOutPut imageOutPut = new ImageOutPut();
        imageOutPut.setForeignKeyId(stroreId);
        imageOutPut.setImageSource("store");
        //通过mq消息队列发送给资源模块绑定图片关系
//        amqpTemplate.convertAndSend("DTO.image.exchange", "DTO.image.store", JsonUtil.toJson(imageOutPut));

        Map<String, Object> properties = new HashMap<>();
        properties.put("imageIds", imageIdlist);

        String exchange = "image.exchange";
        String routingKey = "image.store";

        rabbitSender.sendMessageToMQ(imageOutPut, properties, exchange, routingKey);
    }

    /**
     * 隐藏显示商户
     *
     * @param id
     * @param statusShow
     * @param storeStatus
     * @return
     */
    public Integer displayStore(String id, Integer statusShow, Integer storeStatus) {
        Date date = new Date();
        Store localStore = storeRepository.findByIdAndStatusShow(id, statusShow, storeStatus);
        if (statusShow == 0) {
            localStore.setStatusShow(1);
            localStore.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
            storeRepository.saveAndFlush(localStore);
            List<StoreLabel> storeLabels = storeLabelRepository.findByStoreIdManageent(localStore.getId());
            //解除商户标签关系
            for (StoreLabel storeLabel : storeLabels) {
                storeLabel.setUpdateTime(DateUtils.currentDate());
                storeLabel.setStatusShow(1);
                storeLabelRepository.saveAndFlush(storeLabel);
            }

        } else {
            localStore.setStatusShow(0);
            localStore.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
            storeRepository.saveAndFlush(localStore);
            //重新绑定商户标签关系
            List<StoreLabel> storeLabels = storeLabelRepository.findByStoreIdManageent(localStore.getId());
            for (StoreLabel storeLabel : storeLabels) {
                storeLabel.setUpdateTime(DateUtils.currentDate());
                storeLabel.setStatusShow(0);
                storeLabelRepository.saveAndFlush(storeLabel);
            }
        }
        return localStore.getStatusShow();
    }

    /**
     * 修改商户信息
     *
     * @param request
     * @return
     */
    public boolean updateStore(StoreRequest request) {

        Date date = new Date();
        Store localStore = storeRepository.findByStoreId(request.getId());
        if (localStore == null) {
            return false;
        }
        BeanUtil.copyProperties(request, localStore, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        if (request.getCommercialId() != null) {
            Commercial commercial = commercialRepository.findByCommercialId(request.getCommercialId());
            localStore.setCommercialId(request.getCommercialId());
            localStore.setStoreCommercial(commercial.getName());
        }
        if (request.getFloorId() != null) {
            localStore.setFloorId(request.getFloorId());
            Floor floor = floorRepository.findByIdAndStatusShow(request.getFloorId());
            localStore.setStoreFloor(floor.getFloorName());
        }
        List<StoreLabel> storeLabels = storeLabelRepository.findByStoreIdManageent(localStore.getId());
        //先解除旧的商户标签关系
        for (StoreLabel storeLabel : storeLabels) {
            storeLabel.setUpdateTime(DateUtils.currentDate());
            storeLabel.setStatusShow(1);
            storeLabel.setStatusRemove(1);
            storeLabelRepository.saveAndFlush(storeLabel);
        }
        //再绑定新的商户标签关系
        if (request.getLabelIdList() != null && request.getLabelIdList().size() > 0) {
            for (String labelId : request.getLabelIdList()) {
                StoreLabel storeLabel = new StoreLabel();
                storeLabel.setId(UUIDGenerator.getUUID());
                storeLabel.setLabelId(labelId);
                storeLabel.setStoreId(localStore.getId());
                storeLabel.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                storeLabel.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                storeLabel.setStatusShow(0);
                storeLabel.setStatusRemove(0);
                storeLabelRepository.saveAndFlush(storeLabel);
            }
        }
        bandingImageShip(localStore.getId(), request.getImageIds());
        storeRepository.saveAndFlush(localStore);
        return true;
    }

    /**
     * 删除商户（软删除）
     *
     * @param id
     * @return
     */
    public Integer removeStore(String id) {
        Date date = new Date();
        Store localStore = storeRepository.findByStoreId(id);
        localStore.setStatusRemove(1);
        localStore.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        List<StoreLabel> storeLabels = storeLabelRepository.findByStoreIdManageent(localStore.getId());
        //先解除旧的商户标签关系
        for (StoreLabel storeLabel : storeLabels) {
            storeLabel.setUpdateTime(DateUtils.currentDate());
            storeLabel.setStatusShow(1);
            storeLabel.setStatusRemove(1);
            storeLabelRepository.saveAndFlush(storeLabel);
        }
        storeRepository.saveAndFlush(localStore);
        return localStore.getStatusRemove();
    }

    public PageDTO<StoreDTO> findAllStore(StoreRequest request) {
        Integer page = request.getPage();
        Integer size = request.getSize();

        String to = request.getToDate();
        String from = request.getFromDate();
        String keyword = request.getKeyword();
        //分页查询所有申请记录
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page, size, sort);


        Page<Store> paged = storeRepository.findAll((Specification<Store>) (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (StringUtil.isNotEmpty(keyword)) {
                Predicate p1 = cb.like(root.get("storeName").as(String.class), "%" + keyword + "%");
                Predicate p2 = cb.or(cb.like(root.get("phone").as(String.class), "%" + keyword + "%"), p1);
                Predicate p3 = cb.or(cb.like(root.get("storeFloor").as(String.class), "%" + keyword + "%"), p2);
                Predicate p4 = cb.or(cb.like(root.get("storeCommercial").as(String.class), "%" + keyword + "%"), p3);

                predicates.add(p4);

            }

            if (StringUtil.isNotEmpty(from)) {
                Date startOfDay = DateUtils.getStartOfDay(DateUtils.strToDate(from, DateUtils.DATE));

                predicates.add(cb.greaterThanOrEqualTo(root.get("createTime").as(Date.class), startOfDay));
            }
            if (StringUtil.isNotEmpty(to)) {
                Date endOfDay = DateUtils.getEndOfDay(DateUtils.strToDate(to, DateUtils.DATE));
                predicates.add(cb.lessThanOrEqualTo(root.get("createTime").as(Date.class), endOfDay));
            }


            predicates.add(cb.equal(root.get("statusRemove").as(Integer.class), 0));
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);

        List<Store> stores = paged.getContent();
        List<StoreDTO> storeDTOS = new ArrayList<>();
        for (Store store : stores) {
            StoreDTO storeDTO = new StoreDTO();
            //通过映射关系来赋值 //TODO 断点看一下
            BeanUtils.copyProperties(store, storeDTO);
            //封装标签到storeDTO中
            List<StoreLabel> storeLabels = storeLabelRepository.findByStoreId(store.getId());
            List<String> labelIdList = new LinkedList<>();
            for (StoreLabel storeLabel : storeLabels) {
                labelIdList.add(storeLabel.getLabelId());
            }
            storeDTO.setLabelIdList(labelIdList);
            storeDTOS.add(storeDTO);
        }

        PageDTO<StoreDTO> pageDTO = new PageDTO<>();
        pageDTO.setTotal(paged.getTotalElements());
        pageDTO.setList(storeDTOS);
        pageDTO.setTotalPage(paged.getTotalPages());
        pageDTO.setPage(page);
        pageDTO.setPageSize(size);
        pageDTO.setKeyword(keyword);
        pageDTO.setFromDate(from);
        pageDTO.setToDate(to);
        return pageDTO;
    }

    /**
     * 查找商户列表
     *
     * @param request
     * @return
     */
    public List<StoreDTO> storeList(StoreRequest request) {
        List<StoreDTO> storeDTOList = new LinkedList<>();
        List<Store> storeList = null;
        //分页
        Sort sort = new Sort(Sort.Direction.ASC, "sortOrder");
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        Integer storeHot = request.getStoreHot() == null ? 2 : request.getStoreHot();
        Pageable pageable = PageRequest.of(page, size, sort);
        Store store = new Store();
        if (request.getType() == 1) {
            store.setStoreStatus(1);
            store.setStatusShow(0);
            store.setStatusRemove(0);
            if (storeHot == 1) {
                store.setStoreHot(storeHot);
            } else if (storeHot == 0) {
                store.setStoreHot(storeHot);
            } else {
                System.out.println("查询所有商户");
            }
        } else {
            store.setStatusRemove(0);
        }
        Example<Store> example = Example.of(store);
        Page<Store> findAll = storeRepository.findAll(example, pageable);
        storeList = findAll.getContent();
        for (Store localStore : storeList) {
            StoreDTO storeDTO = new StoreDTO();
            BeanUtils.copyProperties(localStore, storeDTO);
            storeDTOList.add(storeDTO);
        }
        return storeDTOList;
    }

    /**
     * 根据商户id查找对应商户
     *
     * @param request
     * @return
     */
    public StoreDTO query(StoreRequest request) {
        Store localStore = null;
        Date date = new Date();
        if (request.getType() == 1) {
            localStore = storeRepository.findByIdAndStatusShow(request.getId(), 0, 1);
        } else {
            localStore = storeRepository.findByStoreId(request.getId());
        }

        if (null != request.getQueryStatus() && request.getQueryStatus() == 0) {
            History history = historyReposity.queryByUserIdAndStoreId(request.getUserId(), localStore.getId());
            if (history != null) {
                history.setStatusRemove(0);
                history.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                historyReposity.saveAndFlush(history);
            } else {
                History localHistory = new History();
                localHistory.setId(UUIDGenerator.getUUID());
                localHistory.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                localHistory.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                localHistory.setStatusShow(0);
                localHistory.setStatusRemove(0);
                localHistory.setStoreId(localStore.getId());
                localHistory.setCountent(localStore.getStoreName());
                localHistory.setUserId(request.getUserId());
                historyReposity.saveAndFlush(localHistory);
            }
        }
        StoreDTO storeDTO = new StoreDTO();
        if (localStore == null) {
            return null;
        }
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        //返回商铺对优惠券列表
        List<Coupon> couponList = couponService.queryByStoreId(localStore.getId(), page, size);
        storeDTO.setCouponList(couponList);
        BeanUtils.copyProperties(localStore, storeDTO);
        IdDTO idDTO = new IdDTO();
        idDTO.setForeignKeyId(localStore.getId());
        ImageDTO imageDTO = restTemplate.postForObject("http://QUANQUAN-RESOURCE/image/image_query", idDTO, ImageDTO.class);
        List<Object> objectList = new LinkedList<>();
        for (Image image : imageDTO.getImageDTOs()) {
            if (image.getLogo()) {
                localStore.setLogo(image.getImageAddress());
                storeRepository.saveAndFlush(localStore);
                storeDTO.setLogo(image.getImageAddress());
                storeDTO.setLogoId(image.getId());
            } else {
                storeDTO.setBannerId(image.getId());
                Map<String, Object> map = new HashMap<>();
                map.put("pictrue", image.getImageAddress());
                objectList.add(map);
            }
        }
        storeDTO.setImageList(objectList);
        Concern concern = concernRepository.queryByUserIdAndStoreId(request.getUserId(), request.getId());
        if (concern == null) {
            storeDTO.setConcernMark(1);
        } else {
            storeDTO.setConcernMark(concern.getStatusRemove());
        }
        List<StoreLabel> storeLabels = storeLabelRepository.findByStoreId(localStore.getId());
        List<String> labelIdList = new LinkedList<>();
        List<Label> labels = new LinkedList<>();
        for (StoreLabel storeLabel : storeLabels) {
            labelIdList.add(storeLabel.getLabelId());
            Label label = labelRepository.findbyLabelId(storeLabel.getLabelId());
            labels.add(label);
        }
        storeDTO.setLabels(labels);
        storeDTO.setLabelIdList(labelIdList);
        return storeDTO;
    }

    /**
     * 根据楼层查找对应商户列表
     *
     * @param page
     * @param size
     * @param floorName
     * @return
     */
    public List<StoreDTO> queryListByFloor(Integer page, Integer size, String floorName) {
        List<StoreDTO> storeDTOList = new LinkedList<>();
        List<Store> storeList = storeRepository.findByStoreFloor(floorName, page * size, size);

        for (Store store : storeList) {
            StoreDTO storeDTO = new StoreDTO();
            BeanUtils.copyProperties(store, storeDTO);

            //封装标签到storeDTO中
            List<StoreLabel> storeLabels = storeLabelRepository.findByStoreId(store.getId());
            List<String> labelIdList = new LinkedList<>();
            List<Label> labels = new LinkedList<>();
            for (StoreLabel storeLabel : storeLabels) {
                labelIdList.add(storeLabel.getLabelId());
                Label label = labelRepository.findbyLabelId(storeLabel.getLabelId());
                labels.add(label);
            }
            storeDTO.setLabels(labels);
            storeDTO.setLabelIdList(labelIdList);
            storeDTOList.add(storeDTO);
        }
        return storeDTOList;
    }


    /**
     * 通过楼层和业态以及商户标签查找商户列表
     *
     * @param page
     * @param size
     * @param floorName
     * @param commercialName
     * @return
     */
    public List<StoreDTO> queryListByFloorAndCommercial(Integer page, Integer size, String floorName, String commercialName, String labelId) {
        List<StoreDTO> storeDTOList = new LinkedList<>();
        List<Store> storeList = null;
        if (StringUtils.isEmpty(floorName) && StringUtils.isEmpty(commercialName) && StringUtils.isEmpty(labelId)) {
            // TODO 都为空
            storeList = storeRepository.findStore(page * size, size);
        } else if (StringUtils.isEmpty(floorName) && StringUtils.isNotEmpty(commercialName) && StringUtils.isNotEmpty(labelId)) {
            // TODO 楼层为空
            storeList = storeRepository.findByCommercialAndLabelId(commercialName, page * size, size, labelId);
        } else if (StringUtils.isEmpty(commercialName) && StringUtils.isNotEmpty(floorName) && StringUtils.isNotEmpty(labelId)) {
            // TODO 业态为空
            storeList = storeRepository.findByFloorAndLabelId(floorName, page * size, size, labelId);
        } else if (StringUtils.isEmpty(labelId) && StringUtils.isNotEmpty(commercialName) && StringUtils.isNotEmpty(floorName)) {
            // TODO 标签为空
            storeList = storeRepository.findByStoreCommercialAndFloor(commercialName, floorName, page * size, size);
        } else if (StringUtils.isEmpty(labelId) && StringUtils.isEmpty(floorName) && StringUtils.isNotEmpty(commercialName)) {
            // TODO 标签和楼层为空
            storeList = storeRepository.findByStoreCommercial(commercialName, page * size, size);
        } else if (StringUtils.isEmpty(labelId) && StringUtils.isEmpty(commercialName) && StringUtils.isNotEmpty(floorName)) {
            // TODO 标签和业态为空
            storeList = storeRepository.findByStoreFloor(floorName, page * size, size);
        } else if (StringUtils.isEmpty(floorName) && StringUtils.isEmpty(commercialName) && StringUtils.isNotEmpty(labelId)) {
            // TODO 业态和楼层为空
            storeList = storeRepository.findByLabelId(labelId, page * size, size);
        } else {
            // TODO 都不为空
            storeList = storeRepository.findByCommercialAndFloorAndLabelId(commercialName, floorName, labelId, page * size, size);
        }
        for (Store store : storeList) {
            StoreDTO storeDTO = new StoreDTO();
            BeanUtils.copyProperties(store, storeDTO);
            //封装标签到storeDTO中
            List<StoreLabel> storeLabels = storeLabelRepository.findByStoreId(store.getId());
            List<String> labelIdList = new LinkedList<>();
            List<Label> labels = new LinkedList<>();
            for (StoreLabel storeLabel : storeLabels) {
                labelIdList.add(storeLabel.getLabelId());
                Label label = labelRepository.findbyLabelId(storeLabel.getLabelId());
                labels.add(label);
            }
            storeDTO.setLabels(labels);
            storeDTO.setLabelIdList(labelIdList);
            storeDTOList.add(storeDTO);
        }
        return storeDTOList;
    }

    /**
     * 根据业态查找对应商户列表
     *
     * @param page
     * @param size
     * @param name
     * @return
     */
    public List<StoreDTO> queryListByCommercial(Integer page, Integer size, String name) {
        List<StoreDTO> storeDTOList = new LinkedList<>();
        List<Store> storeList = storeRepository.findByStoreCommercial(name, page * size, size);
        for (Store store : storeList) {
            StoreDTO storeDTO = new StoreDTO();
            BeanUtils.copyProperties(store, storeDTO);
            storeDTOList.add(storeDTO);
        }
        return storeDTOList;

    }

    /**
     * 模糊查询商户列表
     *
     * @param page
     * @param size
     * @param storeName
     * @return
     */
    public List<StoreDTO> queryListByStoreName(Integer page, Integer size, String storeName, Integer type) {
        List<StoreDTO> storeDTOList = new LinkedList<>();
        Integer count = page * size;
        List<Store> storeList = null;
        if (type == 1) {
            //前端显示的商户列表
            storeList = storeRepository.queryListByStoreName(count, size, storeName);
        } else {
            storeList = storeRepository.queryBackListByStoreName(count, size, storeName);
        }
        for (Store store : storeList) {
            StoreDTO storeDTO = new StoreDTO();
            BeanUtils.copyProperties(store, storeDTO);

            //封装标签到storeDTO中
            List<StoreLabel> storeLabels = storeLabelRepository.findByStoreId(store.getId());
            List<String> labelIdList = new LinkedList<>();
            List<Label> labels = new LinkedList<>();
            for (StoreLabel storeLabel : storeLabels) {
                labelIdList.add(storeLabel.getLabelId());
                Label label = labelRepository.findbyLabelId(storeLabel.getLabelId());
                labels.add(label);
            }
            storeDTO.setLabels(labels);
            storeDTO.setLabelIdList(labelIdList);
            storeDTOList.add(storeDTO);
        }
        return storeDTOList;
    }

    /**
     * 查看历史商铺
     *
     * @param request
     * @return
     */
    public List<Object> queryByUserId(StoreRequest request) {
        List<Object> objectList = new LinkedList<>();
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        List<History> historyList = historyService.queryByUserId(request.getUserId(), page, size);
        for (History history : historyList) {
            Map<String, Object> map = new HashMap<>();
            map.put("storeId", history.getStoreId());
            map.put("content", history.getCountent());
            objectList.add(map);
        }
        return objectList;
    }

    /**
     * 关注商户列表
     *
     * @param request
     * @return
     */
    public List<StoreDTO> queryConcernList(StoreRequest request) {
        List<StoreDTO> storeDTOList = new LinkedList<>();
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        List<Concern> concernList = concernService.queryByUserId(request.getUserId(), page, size);
        for (Concern concern : concernList) {
            StoreDTO storeDTO = new StoreDTO();
            Store store = storeRepository.findByIdAndStatusShow(concern.getStoreId(), 0, 1);
            if (store != null) {
                BeanUtils.copyProperties(store, storeDTO);

                //封装标签到storeDTO中
                List<StoreLabel> storeLabels = storeLabelRepository.findByStoreId(store.getId());
                List<String> labelIdList = new LinkedList<>();
                List<Label> labels = new LinkedList<>();
                for (StoreLabel storeLabel : storeLabels) {
                    labelIdList.add(storeLabel.getLabelId());
                    Label label = labelRepository.findbyLabelId(storeLabel.getLabelId());
                    labels.add(label);
                }
                storeDTO.setLabels(labels);
                storeDTO.setLabelIdList(labelIdList);
                storeDTOList.add(storeDTO);
            }
        }
        return storeDTOList;
    }


    /**
     * 根据idList查找商铺
     *
     * @param idList
     * @return
     */
    public List<StoreDTO> queryByIdList(List<String> idList) {
        List<StoreDTO> storeDTOList = new LinkedList<>();
        for (String id : idList) {
            Store store = storeRepository.findByStoreNum(id);
            StoreDTO storeDTO = new StoreDTO();
            if (store != null) {
                BeanUtils.copyProperties(store, storeDTO);
                storeDTOList.add(storeDTO);
            }
        }
        return storeDTOList;
    }


    /**
     * 根据idList查找商铺
     *
     * @param idList
     * @return
     */
    public List<StoreDTO> queryByIdLists(List<String> idList) {
        List<StoreDTO> storeDTOList = new LinkedList<>();
        for (String id : idList) {
            Store store = storeRepository.findByStoreId(id);
            StoreDTO storeDTO = new StoreDTO();
            if (store != null) {
                BeanUtils.copyProperties(store, storeDTO);
                storeDTOList.add(storeDTO);
            }
        }
        return storeDTOList;
    }

    /**
     * 根据id查询商户
     *
     * @param storeId
     * @return
     */
    public Store findStoreByStoreId(String storeId) throws StoreException {
        Store store = storeRepository.findByStoreId(storeId);
        if (store == null) {
            throw new StoreException("该商户不存在");
        }
        return store;
    }

    /**
     * 查找商户列表
     *
     * @return
     */
    public StoreInfoDTO list() {
        StoreInfoDTO storeInfoDTO = new StoreInfoDTO();
        List<StoreDTO> storeDTOList = new LinkedList<>();
        List<Store> storeList = null;
        //分页
        storeList = storeRepository.findStoreList();
        for (Store localStore : storeList) {
            StoreDTO storeDTO = new StoreDTO();
            BeanUtils.copyProperties(localStore, storeDTO);

            //封装标签到storeDTO中
            List<StoreLabel> storeLabels = storeLabelRepository.findByStoreId(localStore.getId());
            List<String> labelIdList = new LinkedList<>();
            List<Label> labels = new LinkedList<>();
            for (StoreLabel storeLabel : storeLabels) {
                labelIdList.add(storeLabel.getLabelId());
                Label label = labelRepository.findbyLabelId(storeLabel.getLabelId());
                labels.add(label);
            }
            storeDTO.setLabels(labels);
            storeDTO.setLabelIdList(labelIdList);
            storeDTOList.add(storeDTO);
        }
        storeInfoDTO.setStoreDTOS(storeDTOList);
        return storeInfoDTO;
    }


    /**
     * 根据关键词查询商户名称，商户业态，商户楼层等功能使用
     *
     * @param keyword
     * @return
     */
    public List<StoreDTO> findListByKeyword(String keyword) {
        List<Store> storeList = storeRepository.findAll((Specification<Store>) (root, query, criteriaBuilder) -> {
            Predicate p = criteriaBuilder.like(root.get("storeName").as(String.class), "%" + keyword + "%");
            Predicate p1 = criteriaBuilder.or(criteriaBuilder.like(root.get("storeCommercial").as(String.class), "%" + keyword + "%"), p);
            Predicate p2 = criteriaBuilder.or(criteriaBuilder.like(root.get("storeFloor").as(String.class), "%" + keyword + "%"), p1);
            return query.where(p2).getRestriction();
        });

        List<StoreDTO> storeDTOList = new LinkedList<>();
        for (Store store : storeList) {
            StoreDTO storeDTO = new StoreDTO();
            BeanUtils.copyProperties(store, storeDTO);
            //封装标签到storeDTO中
            List<StoreLabel> storeLabels = storeLabelRepository.findByStoreId(store.getId());
            List<String> labelIdList = new LinkedList<>();
            List<Label> labels = new LinkedList<>();
            for (StoreLabel storeLabel : storeLabels) {
                labelIdList.add(storeLabel.getLabelId());
                Label label = labelRepository.findbyLabelId(storeLabel.getLabelId());
                labels.add(label);
            }
            storeDTO.setLabels(labels);
            storeDTO.setLabelIdList(labelIdList);
            storeDTOList.add(storeDTO);
        }
        return storeDTOList;
    }

    /**
     * 根据关键词查询商户名称，商户业态，商户楼层等功能使用
     *
     * @param keyword
     * @return
     */
    public List<StoreDTO> findListByStoreName(String keyword) {
        List<Store> storeList = storeRepository.findAll((Specification<Store>) (root, query, criteriaBuilder) -> {
            Predicate p = criteriaBuilder.like(root.get("storeName").as(String.class), "%" + keyword + "%");
            return query.where(p).getRestriction();
        });

        List<StoreDTO> storeDTOList = new LinkedList<>();
        for (Store store : storeList) {
            StoreDTO storeDTO = new StoreDTO();
            BeanUtils.copyProperties(store, storeDTO);
            storeDTOList.add(storeDTO);
        }
        return storeDTOList;
    }

    /**
     * 根据数采的数据返回商户id
     *
     * @param shopEntityId
     * @param shopEntityName
     * @return
     */
    public String getStoreId(String shopEntityId, String shopEntityName) {
        Store store = storeRepository.findShopEntityId(shopEntityId);
        if (store != null) {
            if (!store.getStoreName().equals(shopEntityName)) {
                store.setStoreName(shopEntityName);
                storeRepository.saveAndFlush(store);
            }
            return store.getId();
        }
        return null;
    }

}
